import request from '@/utils/request';
import { TableListParams } from './data.d';
import qs from 'qs';

const getRandomuserParams = (params: any) => {
  return {
    pageNo: params.current,
    ...params,
  };
};

//容量单位转换(kb,mb,gb,tb)
function bytesToSize(bytes) {
  if (bytes === 0) return '0 B';
  let k = 1024,
    sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    i = Math.floor(Math.log(bytes) / Math.log(k));
    let n = 3;
    if(i == 1){
      n = 4;
    }
  return (bytes / Math.pow(k, i)).toPrecision(n) + ' ' + sizes[i];
}

//素材列表
export async function materialList(params: TableListParams) {
  params = getRandomuserParams(params);
  return request('/api/material/list', {
    method: 'GET',
    headers: {
      Authorization: localStorage.getItem('token'),
    },
    params,
  }).then((response) => {
    if (response && response.code === 200) {
      //数据转换
      const obj = new Object();
      let list = response.data.list;
      for (var i in list) {
        list[i].key = list[i].id;
        list[i].filename = list[i].filename +'.'+ list[i].ext;
        list[i].resolution = list[i].width + ' x ' + list[i].height;
        let sizeBytes = list[i].size;
        list[i].size = bytesToSize(parseInt(sizeBytes));
        if(list[i].type == "VIDEO"){
          list[i].duration = parseInt(parseInt(JSON.parse(list[i].extraInfo).duration)/1000)+'秒'
        }
      }
      obj['data'] = response.data.list;
      obj['pageCount'] = response.data.pageCount;
      obj['current'] = response.data.pageNo;
      obj['total'] = response.data.totalCount;
      return obj;
    }
  });
}

//素材删除
export async function materialRemove(params: any) {
  return request('/api/material/delete/', {
    headers: {
      Authorization: localStorage.getItem('token'),
    },
    method: 'delete',
    params,
  });
}
//批量素材删除
export async function batchDelete(params: any) {
  return request('/api/material/batchDelete/', {
    headers: {
      Authorization: localStorage.getItem('token'),
    },
    method: 'delete',
    params,
  });
}

//重命名
export async function rename(params: any) {
  return request('/api/material/rename', {
    method: 'PUT',
    headers: {
      Authorization: localStorage.getItem('token'),
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: qs.stringify(params, { arrayFormat: 'indices', allowDots: true }),
  });
}
//分配标签
export async function setTag(params: any) {
  return request('/api/material/tag', {
    method: 'PUT',
    headers: {
      Authorization: localStorage.getItem('token'),
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: qs.stringify(params, { arrayFormat: 'indices', allowDots: true }),
  });
}
//素材详情
export async function materialDetail(id: number) {
  return request(`/api/material/detail/${id}`, {
    headers: {
      Authorization: localStorage.getItem('token'),
    },
  });
}
